package com.lsm.sm.action;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.lsm.sm.entity.User;
import com.lsm.sm.service.UserService;

@Controller("userAction")
@Scope("prototype")
public class UserAction implements Serializable{
	private static final long serialVersionUID = 763846616153674779L;
	
	@Resource
	private UserService userService;
	
	private User user;
	private String error;
	private InputStream stream;
	
	public String register(){
		try{
			userService.register( user );
			return "register";
		}catch( Exception e ){
			dealException(e);
			return "error";
		}
	}
	
	public String login(){
		try{
			user = userService.login( user );
			return "login";
		}catch( Exception e ){
			dealException(e);
			return "error";
		}
	}
	
	public String logout(){
		userService.logout();
		return "success";
	}
	
	public String update(){
		try{
			user = userService.getUser();
			return "update";
		}catch( Exception e ){
			dealException(e);
			return "error";
		}
	}
	
	public String saveUpdate(){
		try{
			userService.update( user );
			setError("修改成功!");
		}catch( Exception e ){
			dealException(e);
			return "error";
		}
		return "saveUpdate";
	}
	
	public String checkExist(){
		try{
			setError( "哦耶！你的账号独一无二&true" );
			User u2 = userService.checkExist( user );
			if( u2 != null ){
				setError( "啊哦！该账号已被占用" );
			}
			stream = new ByteArrayInputStream( getError().getBytes( "utf8" ) );
			return "userExist";
		}catch(IOException e ){
			dealException( e );
			return "userExist";
		}catch( Exception e ){
			dealException(e);
			return "userExist";
		}
	}
	
	private void dealException(Exception e) {
		setError( e.getMessage() );
		System.out.println( e.getMessage() );
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}
	
	public InputStream getStream() {
		return stream;
	}

	public void setStream(InputStream stream) {
		this.stream = stream;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}